package test.ws;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import test.PerformanceAnalyze;

public class TimeClientHandler extends ChannelInboundHandlerAdapter {

    PerformanceAnalyze performanceAnalyze = new PerformanceAnalyze();

    @Override
    public void channelActive(final ChannelHandlerContext ctx) {
        ByteBuf time = ctx.alloc().buffer(8); // (2)
        time.writeLong(System.nanoTime());
        ctx.writeAndFlush(time); // (3)
        time.clear();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf m = (ByteBuf) msg; // (1)
        try {
            while (m.isReadable() && m.readerIndex()+8 <= m.readableBytes()) {
                performanceAnalyze.delay((System.nanoTime()-m.readLong())/2);
                performanceAnalyze.meter();
            }
//            ctx.close();
        } finally {
            m.release();
        }

        for (int i = 0; i < 200; i++) {
            ByteBuf time = ctx.alloc().buffer(8); // (2)
            time.writeLong(System.nanoTime());
            ctx.write(time); // (3)
//            time.clear();
        }
        ctx.flush();



    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}